import React, { useEffect, useState } from 'react';
import { Table, Button, Modal, Form, Input, InputNumber, Upload, Select, message, Card, Tag, Image, Switch } from 'antd';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { getProductList, createProduct, updateProduct, enableProduct, searchProductByName } from '../api/product';

const { TextArea } = Input;

// 商品分类选项
const categories = [
  { label: '电子产品', value: 'electronics' },
  { label: '服装', value: 'clothing' },
  { label: '食品', value: 'food' },
  { label: '书籍', value: 'books' },
  { label: '家用电器', value: 'home_appliances' },
  { label: '美妆', value: 'beauty' },
  { label: '运动', value: 'sports' },
  { label: '家具', value: 'furniture' },
  { label: '玩具', value: 'toys' },
  { label: '其他', value: 'others' },
];

interface ProductItem {
  id: number;
  productName: string;
  productImg: string;
  price: number;
  enableFlag: boolean;
  createTime: string;
  stock: number;
  productDesc: string;
  sortIndex: number;
}

const ProductManage: React.FC = () => {
  const [data, setData] = useState<ProductItem[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    showSizeChanger: true,
    pageSizeOptions: ['5', '10', '20', '50'],
  });
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [switchLoading, setSwitchLoading] = useState<{[key:number]: boolean}>({});
  const [stockEdit, setStockEdit] = useState<{[key:number]: number}>({});
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editRecord, setEditRecord] = useState<ProductItem | null>(null);
  const [editForm] = Form.useForm();
  const [editFileList, setEditFileList] = useState<UploadFile[]>([]);
  const [editLoading, setEditLoading] = useState(false);
  const [searchValue, setSearchValue] = useState('');
  const [searching, setSearching] = useState(false);

  const fetchData = async (page = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const res = await getProductList(page, pageSize);
      if (res.data && res.data.records) {
        setData(res.data.records);
        setTotal(res.data.total || 0);
      } else if (res.data && res.data.data && res.data.data.records) {
        setData(res.data.data.records);
        setTotal(res.data.data.total || 0);
      } else {
        setData([]);
        setTotal(0);
      }
    } catch (e) {
      message.error('获取商品列表失败');
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchData(pagination.current as number, pagination.pageSize as number);
    // eslint-disable-next-line
  }, []);

  const handleTableChange = (pag: TablePaginationConfig) => {
    setPagination(pag);
    fetchData(pag.current as number, pag.pageSize as number);
  };

  const columns: ColumnsType<ProductItem> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '商品名称',
      dataIndex: 'productName',
      key: 'productName',
      width: 180,
    },
    {
      title: '商品图片',
      dataIndex: 'productImg',
      key: 'productImg',
      width: 100,
      render: (img: string) => img ? <Image src={img} width={50} height={50} style={{ objectFit: 'cover' }} /> : '-',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      width: 100,
      render: (price: number) => `￥${price.toFixed(2)}`,
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      width: 100,
      render: (stock: number) => stock,
    },
    {
      title: '上架状态',
      dataIndex: 'enableFlag',
      key: 'enableFlag',
      width: 120,
      render: (flag: boolean, record: ProductItem) => (
        <Switch
          checked={flag}
          checkedChildren="上架"
          unCheckedChildren="下架"
          loading={switchLoading[record.id]}
          onChange={checked => handleEnable(record, checked)}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: ProductItem) => (
        <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
      ),
    },
  ];

  // 处理新增商品
  const handleAdd = async () => {
    try {
      const values = await form.validateFields();
      const file = fileList[0]?.originFileObj;
      if (!file) {
        message.error('请上传商品图片');
        return;
      }
      await createProduct(values, file);
      message.success('添加商品成功');
      setIsModalVisible(false);
      form.resetFields();
      setFileList([]);
      fetchData(pagination.current as number, pagination.pageSize as number);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  // 处理删除商品
  const handleDelete = (id: number) => {
    setData(data.filter(p => p.id !== id));
    message.success('删除商品成功');
  };

  // 处理图片上传
  const handleUploadChange = ({ fileList: newFileList }: { fileList: UploadFile[] }) => {
    setFileList(newFileList);
  };

  const handleEnable = async (record: ProductItem, flag: boolean) => {
    setSwitchLoading(prev => ({ ...prev, [record.id]: true }));
    try {
      await enableProduct(record.id, flag);
      message.success(flag ? '已上架' : '已下架');
      fetchData(pagination.current as number, pagination.pageSize as number);
    } catch (e) {
      message.error('操作失败');
    }
    setSwitchLoading(prev => ({ ...prev, [record.id]: false }));
  };

  const handleStockChange = (record: ProductItem, value: string) => {
    setStockEdit(prev => ({ ...prev, [record.id]: Number(value) }));
  };

  const handleStockBlur = async (record: ProductItem, value: string) => {
    const newStock = Number(value);
    if (isNaN(newStock) || newStock < 0) {
      message.error('库存不能为负数');
      return;
    }
    setSwitchLoading(prev => ({ ...prev, [record.id]: true }));
    try {
      await updateProduct({ id: record.id, stock: newStock });
      message.success('库存已更新');
      fetchData(pagination.current as number, pagination.pageSize as number);
    } catch (e) {
      message.error('库存更新失败');
    }
    setSwitchLoading(prev => ({ ...prev, [record.id]: false }));
  };

  const handleEdit = (record: ProductItem) => {
    setEditRecord(record);
    setEditModalVisible(true);
    editForm.setFieldsValue({
      id: record.id,
      productName: record.productName,
      price: record.price,
      stock: Number(record.stock ?? 0),
      productDesc: record.productDesc,
      sortIndex: Number(record.sortIndex ?? 1),
    });
    setEditFileList(record.productImg ? [{
      uid: '-1',
      name: '图片',
      status: 'done',
      url: record.productImg,
    }] : []);
  };

  const handleEditCancel = () => {
    setEditModalVisible(false);
    setEditRecord(null);
    setEditFileList([]);
    editForm.resetFields();
  };

  const handleEditOk = async () => {
    try {
      const values = await editForm.validateFields();
      setEditLoading(true);
      const params: any = {};
      Object.keys(values).forEach(key => {
        if (values[key] !== undefined && values[key] !== null && values[key] !== '') {
          params[key] = values[key];
        }
      });
      params.id = values.id;
      let productImg = editRecord?.productImg;
      const file = editFileList[0]?.originFileObj;
      if (file) {
        productImg = '';
      } else if (editFileList[0]?.url) {
        productImg = editFileList[0].url;
      }
      if (productImg && productImg !== editRecord?.productImg) params.productImg = productImg;
      await updateProduct(params, file);
      message.success('商品信息已更新');
      setEditModalVisible(false);
      setEditRecord(null);
      setEditFileList([]);
      editForm.resetFields();
      fetchData(pagination.current as number, pagination.pageSize as number);
    } catch (e) {
      message.error('保存失败');
    }
    setEditLoading(false);
  };

  const handleSearch = async () => {
    if (!searchValue) {
      fetchData(1, pagination.pageSize as number);
      setPagination({ ...pagination, current: 1 });
      return;
    }
    setSearching(true);
    setLoading(true);
    try {
      const res = await searchProductByName(searchValue);
      if (res.data && res.data.data) {
        setData([res.data.data]);
        setTotal(1);
        setPagination({ ...pagination, current: 1, total: 1 });
      } else {
        setData([]);
        setTotal(0);
        setPagination({ ...pagination, current: 1, total: 0 });
        message.info('未找到该商品');
      }
    } catch (e) {
      message.error('查询失败');
    }
    setLoading(false);
    setSearching(false);
  };

  return (
    <div style={{ padding: 24 }}>
      <Card>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <h2 style={{ margin: 0 }}>商品管理</h2>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => setIsModalVisible(true)}>
            新增商品
          </Button>
        </div>
        <div style={{ marginBottom: 16, display: 'flex', gap: 8 }}>
          <Input
            placeholder="请输入商品名称"
            value={searchValue}
            onChange={e => setSearchValue(e.target.value)}
            style={{ width: 220 }}
            onPressEnter={handleSearch}
            allowClear
          />
          <Button type="primary" onClick={handleSearch} loading={searching}>搜索</Button>
          <Button onClick={() => { setSearchValue(''); fetchData(1, pagination.pageSize as number); setPagination({ ...pagination, current: 1 }); }}>重置</Button>
        </div>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={data}
          loading={loading}
          pagination={{
            ...pagination,
            total,
            showTotal: t => `共 ${t} 条`,
          }}
          onChange={handleTableChange}
          bordered
        />
      </Card>

      <Modal
        title="新增商品"
        open={isModalVisible}
        onOk={handleAdd}
        onCancel={() => {
          setIsModalVisible(false);
          form.resetFields();
          setFileList([]);
        }}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ category: 'food' }}
        >
          <Form.Item
            name="productName"
            label="商品名称"
            rules={[{ required: true, message: '请输入商品名称' }]}
          >
            <Input placeholder="请输入商品名称" />
          </Form.Item>

          <Form.Item
            name="price"
            label="商品价格"
            rules={[{ required: true, message: '请输入商品价格' }]}
          >
            <InputNumber
              min={0}
              precision={2}
              style={{ width: '100%' }}
              placeholder="请输入商品价格"
              prefix="￥"
            />
          </Form.Item>

          <Form.Item
            name="category"
            label="商品分类"
            rules={[{ required: true, message: '请选择商品分类' }]}
          >
            <Select options={categories} placeholder="请选择商品分类" />
          </Form.Item>

          <Form.Item
            name="productDesc"
            label="商品描述"
            rules={[{ required: true, message: '请输入商品描述' }]}
          >
            <TextArea rows={4} placeholder="请输入商品描述" />
          </Form.Item>

          <Form.Item
            name="sortIndex"
            label="排序"
            rules={[{ required: true, message: '请选择排序' }]}
            initialValue={1}
          >
            <Select options={Array.from({ length: 10 }, (_, i) => ({ label: i + 1, value: i + 1 }))} placeholder="请选择排序" />
          </Form.Item>

          <Form.Item
            name="stock"
            label="库存"
            rules={[{ required: true, message: '请输入库存' }]}
            initialValue={0}
          >
            <Input type="number" min={0} placeholder="请输入库存" />
          </Form.Item>

          <Form.Item
            label="商品图片"
            rules={[{ required: true, message: '请上传商品图片' }]}
          >
            <Upload
              listType="picture"
              maxCount={1}
              fileList={fileList}
              onChange={handleUploadChange}
              beforeUpload={() => false}
            >
              <Button icon={<UploadOutlined />}>上传图片</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="编辑商品"
        open={editModalVisible}
        onOk={handleEditOk}
        onCancel={handleEditCancel}
        confirmLoading={editLoading}
        destroyOnClose
      >
        <Form form={editForm} layout="vertical">
          <Form.Item name="id" style={{ display: 'none' }}><Input /></Form.Item>
          <Form.Item name="productName" label="商品名称">
            <Input />
          </Form.Item>
          <Form.Item name="price" label="商品价格">
            <Input type="number" min={0} />
          </Form.Item>
          <Form.Item name="stock" label="库存">
            <Input type="number" min={0} />
          </Form.Item>
          <Form.Item name="productDesc" label="商品描述">
            <Input />
          </Form.Item>
          <Form.Item name="sortIndex" label="排序">
            <Input type="number" min={1} max={10} />
          </Form.Item>
          <Form.Item label="商品图片">
            <Upload
              listType="picture"
              maxCount={1}
              fileList={editFileList}
              onChange={({ fileList }) => setEditFileList(fileList)}
              beforeUpload={() => false}
            >
              <Button icon={<UploadOutlined />}>上传图片</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ProductManage; 